package ru.lukyanets.transmission.client.action;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import javafx.event.ActionEvent;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.control.Dialog;
import javafx.stage.Stage;
import ru.lukyanets.transmission.client.app.PrimaryStage;
import ru.lukyanets.transmission.client.config.ConnectionConfig;
import ru.lukyanets.transmission.client.connection.ConnectionInfo;
import ru.lukyanets.transmission.client.ui.controller.ConnectionsDialogController;
import ru.lukyanets.transmission.client.util.DialogUtil;
import ru.lukyanets.transmission.client.util.LocalizationUtil;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.ResourceBundle;

/**
 * @author slukyanets
 */
@Singleton
public class EditConnectionsAction extends AbstractAction {
    private static final String FXML_FILE = "/fxml/connectionsDialog.fxml";

    private Dialog<List<ConnectionInfo>> dialog;

    @Inject
    @PrimaryStage Stage primaryStage;

    @Inject
    ConnectionConfig config;

    @Override
    protected void performAction(ActionEvent event) {
        load(); // lazy loading of fxml content

        if (dialog != null) {
            dialog.showAndWait().ifPresent(connections -> {
                config.set(connections);
                config.store();
            });
        }
    }

    private void load() {
        if (dialog == null) {
            ResourceBundle bundle = LocalizationUtil.getResourceBundle();
            FXMLLoader loader = new FXMLLoader(getClass().getResource(FXML_FILE), bundle);
            try {
                Node content = loader.load();
                ConnectionsDialogController controller = loader.getController();

                dialog = new Dialog<>();
                dialog.initOwner(primaryStage);
                dialog.setTitle(LocalizationUtil.getString("dialog.connections.title"));
                dialog.setResizable(false);

                dialog.getDialogPane().getButtonTypes().addAll(DialogUtil.YES, DialogUtil.CANCEL);
                dialog.getDialogPane().setContent(content);

                dialog.setResultConverter(button -> button == DialogUtil.YES ? controller.getConnections() : null);

                dialog.setOnShowing(val -> {
                    List<ConnectionInfo> connections = new LinkedList<>(config.getConnections());
                    controller.setConnections(connections);
                });
            } catch (IOException e) {
                DialogUtil.showError(e.getMessage());
            }
        }
    }
}
